import urllib
from google.appengine.ext import db
from django.shortcuts import *
from django.template import RequestContext 
from django.utils.simplejson import *
from django.core.urlresolvers import reverse
from ytcommunity.blog.setting import CATEGORY, RECENT_COMMENT_NUM
from ytbase.model.comment import *
from ytbase.helper import *
from ytcommunity.blog.helper.context import *
import ytbase.view.comment

def add(request, id):
    def filler(comment):
        comment.category = CATEGORY
        return comment
    
    return ytbase.view.comment.add(request, id=id, filler=filler)

def delete(request, id):
    return ytbase.view.comment.delete(request, id=id)

@check_page_cache(True)
def recent_comments(request):
    query = YTComment.all().order('-date').filter('category =', CATEGORY)
    data = query.fetch(RECENT_COMMENT_NUM)
    #filter invalid comments caused by deleted blogs
    data = [d for d in data if db.get(YTComment.ref.get_value_for_datastore(d))]

    def get_url(d):
        return reverse('ytcommunity.blog.view.blog.display', kwargs={'id':str(d.ref.key().id())})

    from django.utils.html import escape, strip_tags
    def transfer(d):
        return {
            'id': d.key().id(),
            'content': escape(strip_tags(d.content)),
            'author': d.author.get_name(),
            'url': get_url(d)
            }
    
    context = [transfer(d) for d in data]
    json = dumps(context)
    return HttpResponse(json, mimetype="application/json")    
